using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using HTCollections.Unsafe;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;

namespace HTCollections
{
    /// <summary>
    /// 用于在 JobSystem 中传递数据
    /// </summary>
    //[NativeContainer]
    [StructLayout(LayoutKind.Sequential)]
    [DebuggerDisplay("Value = {Value}")]
    public unsafe struct JobDataWrap<T> : IDisposable
        where T : unmanaged
    {
        [NativeDisableUnsafePtrRestriction] public T* Ptr;

        public T Value
        {
            get
            {
// #if ENABLE_UNITY_COLLECTIONS_CHECKS
//                 AtomicSafetyHandle.CheckReadAndThrow(mSafety);
// #endif
                return *Ptr;
            }
            set
            {
// #if ENABLE_UNITY_COLLECTIONS_CHECKS
//                 AtomicSafetyHandle.CheckWriteAndThrow(mSafety);
// #endif
                *Ptr = value;
            }
        }

        public Allocator Allocator;

// #if ENABLE_UNITY_COLLECTIONS_CHECKS
//         AtomicSafetyHandle mSafety;
//         [NativeSetClassTypeToNullOnSchedule] DisposeSentinel mDisposeSentinel;
// #endif

        public JobDataWrap(T value, Allocator allocator)
        {
            Allocator = allocator;
            Ptr = UnsafeUtil.Malloc<T>(1, allocator);

// #if ENABLE_UNITY_COLLECTIONS_CHECKS
//             // Create DisposeSentinel and AtomicSafetyHandle
//             DisposeSentinel.Create(out mSafety, out mDisposeSentinel, 0, allocator);
// #endif

            Value = value;
        }

        public JobDataWrap(Allocator allocator) : this(new T(), allocator)
        {
        }

        public void Dispose()
        {
// #if ENABLE_UNITY_COLLECTIONS_CHECKS
//             DisposeSentinel.Dispose(ref mSafety, ref mDisposeSentinel);
// #endif

            UnsafeUtil.Free(Ptr, Allocator);
        }
    }
}